<template>
  <!-- 公告管理主组件 -->
  <div class="class-announcements">
    <!-- 搜索过滤卡片 -->
    <el-card class="filter-card">
      <!-- 响应式布局容器，栅格间距20px -->
      <el-row :gutter="20">
        <!-- 班级搜索栏（占8列） -->
        <el-col :span="8">
          <el-form-item label="教师名称">
            <!-- 班级名称关键词输入框，回车键触发查询 -->
            <el-input
                    v-model="filterForm.teacherName"
                    placeholder="请输入教师名称"
                    @keyup.enter="fetchAnnouncements"
            />
          </el-form-item>
        </el-col>

        <!-- 公告标题搜索栏（占8列） -->
        <el-col :span="8">
          <el-form-item label="公告标题">
            <!-- 公告标题输入框，回车键触发查询 -->
            <el-input
                    v-model="filterForm.title"
                    placeholder="请输入公告标题"
                    @keyup.enter="fetchAnnouncements"
            />
          </el-form-item>
        </el-col>

        <!-- 操作按钮栏（占8列） -->
        <el-col :span="8">
          <el-form-item>
            <!-- 查询按钮（触发数据加载） -->
            <el-button type="primary" @click="fetchAnnouncements">查询</el-button>
            <!-- 重置按钮（清空搜索条件） -->
            <el-button type="default" @click="resetFilter">重置</el-button>
          </el-form-item>
        </el-col>
      </el-row>
    </el-card>

    <!-- 公告列表卡片 -->
    <el-card class="announcement-list-card">
      <!-- 数据表格组件，展示公告列表 -->
      <el-table :data="announcementList" stripe border>
        <!-- 公告标题列 -->
        <el-table-column prop="title" label="公告标题" min-width="100" />
        <!-- 公告内容列 -->
        <el-table-column prop="content" label="公告内容" min-width="80" />
        <!-- 班级列（展示关联班级名称） -->
        <el-table-column prop="classNames" label="班级" min-width="100" />
        <!-- 班级列（展示关联班级名称） -->
        <el-table-column prop="teacherName" label="发布教师" min-width="100" />
        <!-- 发布时间列（展示格式化后的时间） -->
        <el-table-column prop="publishTime" label="发布时间" min-width="100" />
        <!-- 操作列（查看/编辑/删除按钮） -->
        <el-table-column label="操作" min-width="100">
          <template #default="scope">
            <div class="table-actions">
              <el-button type="primary" size="small" @click="handleView(scope.row)">查看</el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页组件 -->
      <el-pagination
              class="pagination"
              background
              layout="total, sizes, prev, pager, next, jumper"
              :total="total"
              :page-sizes="[10, 20, 30, 40]"
              :page-size="pageSize"
              :current-page="currentPage"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
      />
    </el-card>
    <!-- 公告详情弹窗 -->
    <el-dialog v-model="viewDialogVisible" title="公告详情" width="50%">
      <el-card>
        <!-- 详情头部 -->
        <div class="detail-header">
          <h3 class="detail-title">{{ viewAnnouncement.title }}</h3>
          <!-- 标题 -->
          <!-- 元数据信息（班级、发布者、时间、状态） -->
          <div class="detail-meta">
            <span class="detail-meta-item">发布教师：{{ viewAnnouncement.teacherName }}</span>
            <span class="detail-meta-item">发布班级：{{ viewAnnouncement.classNames }}</span>
            <span class="detail-meta-item">发布时间：{{ viewAnnouncement.publishTime }}</span>
          </div>
        </div>
        <!-- 富文本内容展示（需注意XSS安全） -->
        <div class="detail-content" v-html="viewAnnouncement.content"></div>
      </el-card>

      <!-- 详情弹窗关闭按钮 -->
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="viewDialogVisible = false">关闭</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
  import { ref, reactive, onMounted } from "vue";
  import axios from "axios";
  import { ElMessage, ElMessageBox } from "element-plus";
  const filterForm = reactive({
    teacherName: "", // 班级名称关键词（用于模糊查询）
    title: "" // 公告标题关键词
  });

  // 详情展示数据（响应式）
  const viewAnnouncement = reactive({
    title: "",
    classNames: "", // 班级名称（展示用）
    publishTime: "", // 发布时间（格式化后）
    content: "",
    teacherName: ""
  });

  // 列表数据相关
  const announcementList = ref([]); // 公告列表数据
  const total = ref(0); // 总数据量
  const pageSize = ref(10); // 每页条数
  const currentPage = ref(1); // 当前页码
  const viewDialogVisible = ref(false); // 详情弹窗显示状态

  // 生命周期钩子
  onMounted(async () => {
    // 初始化时加载班级列表（可能用于后续优化为下拉选择）
    // 初始化时加载公告列表
    await fetchAnnouncements();
  });

  const fetchAnnouncements = async () => {
    try {
      // 构建请求参数（包含分页和搜索条件）
      const formData = new FormData();
      formData.append("classIds", localStorage.getItem("classId"));
      formData.append("page", currentPage.value);
      formData.append("size", pageSize.value);
      formData.append("title", filterForm.title);
      formData.append("teacherName", filterForm.teacherName);
      // console.log(formData);

      // 调用接口获取数据
      const response = await axios.post(
              "/notifications/getNotificationList",
              formData
      );
      if (response.data.flag == false) {
        ElMessage.error("未查询到信息");
        announcementList.value=[];
        total.value=0;
      } else {
        // console.log(response);
        // 解析响应数据，进行数据筛选
        console.log(response.data.result)
        const filteredList = response.data.result.map(announcement => {
          return {
            title: announcement.title,
            content: announcement.content,
            classNames: announcement.classNames,
            publishTime: announcement.publishTime,
            notificationId: announcement.notificationId,
            teacherName: announcement.teacherName
          };
        });
        announcementList.value = filteredList;
        total.value = response.data.total;
      }
    } catch (error) {
      if (process.env.NODE_ENV === "development") {
        console.error("完整错误信息", error.response || error);
      }
      console.error("获取公告列表失败", error);
      ElMessage.error("获取公告列表失败，请稍后重试");
    }
  };

  // ------------------------------
  // 操作方法
  // ------------------------------
  // 重置搜索条件
  const resetFilter = () => {
    filterForm.teacherName = "";
    filterForm.title = "";
    // 重置列表和分页状态
    // 恢复默认时的无条件查询
    announcementList.value = [];
    total.value = 0;
    fetchAnnouncements();
  };

  // 查看公告详情
  const handleView = async announcement => {
    try {
      if (announcement != null) {
        viewDialogVisible.value = true; // 显示详情弹窗
        viewAnnouncement.classNames = announcement.classNames;
        viewAnnouncement.content = announcement.content;
        viewAnnouncement.publishTime = announcement.publishTime;
        viewAnnouncement.title = announcement.title;
        viewAnnouncement.teacherName = announcement.teacherName;
      } else {
        ElMessage.error(response.data.message || "获取公告详情失败");
      }
    } catch (error) {
      console.error("获取公告详情失败", error);
      ElMessage.error("获取公告详情失败，请稍后重试");
    }
  };

  // 编辑公告（复用发布弹窗）
  const handleEdit = announcement => {
    console.log(announcement);
    showPublishDialog(announcement); // 传入当前公告数据，填充编辑表单
  };

  // 关闭公告（设置状态为closed）
  const handleClose = async announcement => {
    // 确认对话框
    ElMessageBox.confirm(
            `确定要关闭公告 "${announcement.title}" 吗？关闭后学生将无法查看。`,
            "提示",
            {
              confirmButtonText: "确定",
              cancelButtonText: "取消",
              type: "warning"
            }
    )
  };

  // ------------------------------
  // 分页控制方法
  // ------------------------------
  // 每页条数变化时触发
  const handleSizeChange = newSize => {
    pageSize.value = newSize;
    currentPage.value = 1; // 重置页码为第一页
    fetchAnnouncements();// 重新加载数据
  };

  // 当前页码变化时触发
  const handleCurrentChange = newPage => {
    currentPage.value = newPage;
    fetchAnnouncements(); // 重新加载数据
  };
</script>

<style scoped>
  .class-announcements {
    padding: 20px;
    /* 容器内边距 */
  }

  .filter-card {
    margin-bottom: 20px;
    /* 搜索卡片底部间距 */
  }

  .announcement-list-card {
    min-height: 500px;
    /* 列表卡片最小高度，防止内容较少时布局塌陷 */
  }

  .pagination {
    margin-top: 20px;
    /* 分页组件顶部间距 */
    text-align: right;
    /* 分页按钮右对齐 */
  }

  .detail-header {
    margin-bottom: 20px;
    /* 详情头部底部间距 */
  }

  .detail-title {
    font-size: 20px;
    /* 标题字体大小 */
    font-weight: bold;
    /* 标题加粗 */
    margin-bottom: 10px;
    /* 标题底部间距 */
  }

  .detail-meta {
    color: #909399;
    /* 元数据字体颜色（浅灰色） */
    font-size: 14px;
    /* 元数据字体大小 */
  }

  .detail-meta-item {
    margin-right: 20px;
    /* 元数据项间距 */
  }

  /* .detail-content {
    margin-bottom: 20px;
    height: 100px;
    line-height: 1.8;
  } */
  .detail-content {
    margin-bottom: 20px;
    height: 200px; /* 调整高度以适应内容 */
    padding: 10px; /* 添加内边距 */
    border: 1px solid #dcdfe6; /* 添加边框 */
    border-radius: 4px; /* 添加圆角 */
    background-color: #f5f7fa; /* 添加背景颜色 */
    line-height: 1.8;
    overflow-y: auto; /* 如果内容超出高度，则显示滚动条 */
    word-wrap: break-word; /* 处理长单词换行 */
  }

  /* 样式穿透 */
  ::v-deep .el-table td.el-table__cell div {
    box-sizing: border-box;
    display: block;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
  }
</style>